package com.yang.po;

import com.google.common.collect.Maps;
import com.yang.utils.JsonUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 统一返回结果类
 * @author: Yang Qiang
 * @create: 2021-11-13 16:05
 */
@Data
public class Response {
    Logger logger = LoggerFactory.getLogger(Response.class);

    private String isSuccess;
    private String errorMSG;
    private String subCode;

    private Map result;

    public static Response SUCCESS() {
        return new Response("0", "");
    }

    public static Response SUCCESS(String msg) {
        return new Response("0", msg);
    }

    public static Response SUCCESS(Object result) {
        return SUCCESS().put("detail", result);
    }

    public static Response BUSINESS_FAIL() {
        return new Response("1", "业务级失败");
    }

    public static Response BUSINESS_FAIL(String msg) {
        return new Response("1", msg);
    }

    public static Response SYSTEM_FAIL() {
        return new Response("2", "服务繁忙");
    }

    public static Response SYSTEM_FAIL(String msg) {
        return new Response("2", msg);
    }

    public static Response ParamError() {
        return new Response("9999", "参数错误");
    }

    public Response subCode(String code) {
        return put("subCode", code);
    }

    /**
     * 向result中添加额外的参数
     *
     * @param key
     * @param value
     * @return
     */
    public Response put(String key, Object value) {
        result.put(key, value);
        return this;
    }

    public Response putAll(Map map) {
        if (map != null) {
            result.putAll(map);
        }
        return this;
    }

    public Object get(String key) {
        return result.get(key);
    }

    /*判断是否成功*/
    public boolean isSuccess() {
        return StringUtils.equals(isSuccess, "0");
    }

    /**
     * 修改errorMSG
     *
     * @param msg
     * @return
     */
    public Response msg(String msg) {
        put("errorMSG", msg);
        return this;
    }

    public Map getResult() {
        return result;
    }


    public Response() {
        result = Maps.newHashMap();
    }

    public Response(String isSuccess, String errorMSG) {
        this.isSuccess = isSuccess;
        this.errorMSG = errorMSG;
        result = Maps.newHashMap();
        result.put("isSuccess", isSuccess);
        result.put("errorMSG", errorMSG);
    }

    public String getIsSuccess() {
        return isSuccess;
    }

    public String getErrorMSG() {
        return errorMSG;
    }

    public String toJson() {
        /*所有接口增加返回时间戳字段*/
        result.put("timestamp", System.currentTimeMillis());
        String json = JsonUtil.toJsonWithString(result);
        logger.info("returnData:{}", json);
        return json;
    }
}
